package com.mjduan.myBank.util.email.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Component;

@Component("MailUtil")
public class MailUtil {
	private boolean isSSL = true;
	private String host = "smtp.163.com";
	private int port = 465;
	private String fromEmail = "dmj1161859184@163.com";
	private boolean isAuth = true;
	private String username = "dmj1161859184@163.com";// 不要乱用我的邮箱
	private String password = "jmd1161859184";// 不要乱用我的邮箱
	// 发往哪个邮箱
	private String toEmail;
	// 邮件主题
	private String subject;
	// html格式的内容
	private String contentHtmlFormat;

	/**
	 * 在发送之前需要接收需要的参数
	 * @param toEmail
	 * @param subject
	 * @param contentHtmlFormat
	 * @return
	 *
	 */
	public boolean send(String toEmail, String subject, String contentHtmlFormat) {
		this.toEmail = toEmail;
		this.subject = subject;
		this.contentHtmlFormat = contentHtmlFormat;

		boolean result = process();

		return result;
	}

	private boolean process() {
		Properties props = new Properties();
		props.put("mail.smtp.ssl.enable", isSSL);
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", isAuth);

		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(fromEmail));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
			message.setSubject(subject);
			message.setContent(contentHtmlFormat, "text/html;charset=gb2312");

			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}


	public void setToEmail(String toEmail) {
		this.toEmail = toEmail;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public void setContentHtmlFormat(String contentHtmlFormat) {
		this.contentHtmlFormat = contentHtmlFormat;
	}
	
}
